<template>
    <NavbarComponent />
    <div class="edit-container">
      <el-card class="edit-card">
        <h2 class="title">编辑商品</h2>
        <el-form 
          :model="form" 
          label-width="120px" 
          label-position="top" 
          :rules="rules" 
          ref="formRef"
        >
          <!-- 商品类别 -->
          <el-form-item label="商品类别" prop="category">
            <el-select 
              v-model="form.category"
              multiple
              filterable
              placeholder="请选择商品分类"
              class="category-select"
            >
              <el-option
                v-for="item in categories"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
  
          <!-- 教材信息 -->
          <div v-if="showEducationFields">
            <el-form-item label="年级" prop="grade">
              <el-select
                v-model="form.grade"
                placeholder="请选择年级"
                class="grade-select"
                clearable
              >
                <el-option
                  v-for="grade in grades"
                  :key="grade"
                  :label="grade"
                  :value="grade"
                />
              </el-select>
            </el-form-item>
  
            <el-form-item label="专业" prop="major">
              <el-autocomplete
                v-model="form.major"
                :fetch-suggestions="querySearch"
                placeholder="请输入或选择专业"
                class="major-select"
                :loading="majorsLoading"
              >
                <template #prefix>
                  <el-icon><Collection /></el-icon>
                </template>
              </el-autocomplete>
            </el-form-item>
          </div>
  
          <!-- 商品名称 -->
          <el-form-item label="商品名称" prop="productName">
            <el-input 
              v-model="form.productName" 
              placeholder="请输入商品名称"
              class="custom-input"
              clearable
            >
              <template #prefix>
                <el-icon><Goods /></el-icon>
              </template>
            </el-input>
          </el-form-item>
  
          <!-- 商品价格 -->
          <el-form-item label="商品价格（元）" prop="price">
            <el-input 
              v-model="form.price"
              placeholder="请输入价格"
              class="price-input"
              @input="validatePrice"
            >
              <template #prefix>
                <el-icon><Money /></el-icon>
              </template>
            </el-input>
          </el-form-item>
  
          <!-- 商品介绍 -->
          <el-form-item label="商品介绍" prop="introduction">
            <el-input
              v-model="form.introduction"
              type="textarea"
              :rows="4"
              placeholder="请输入商品详细信息"
              class="description-input"
              resize="none"
              show-word-limit
              maxlength="300"
            />
          </el-form-item>
  
          <!-- 图片上传 -->
          <el-form-item label="商品图片" prop="images">
            <el-upload
              v-model:file-list="form.images"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="5"
              :on-exceed="handleExceed"
              multiple
              :on-change="handleImageChange"
              class="image-uploader"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <img :src="file.url" class="uploaded-image" />
                <span class="image-actions">
                  <span class="image-preview" @click.stop="handlePictureCardPreview(file)">
                    <el-icon><ZoomIn /></el-icon>
                  </span>
                  <span class="image-delete" @click.stop="handleRemove(file)">
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </template>
            </el-upload>
          </el-form-item>
  
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button 
              type="info"
              class="cancel-btn"
              @click="handleCancel"
            >
              取消修改
            </el-button>
            <el-button 
              type="primary" 
              class="submit-btn"
              @click="handleSubmit"
              :loading="loading"
            >
              {{ loading ? '提交中...' : '确认修改' }}
            </el-button>
          </div>
        </el-form>
      </el-card>
  
      <!-- 图片预览 -->
      <el-dialog v-model="dialogVisible" title="图片预览" width="60%">
        <img :src="previewImageUrl" class="preview-image" />
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  import NavbarComponent from '@/components/components/NavbarComponent.vue'
  import { Goods, Money, Plus, ZoomIn, Delete, Collection } from '@element-plus/icons-vue'
  
  const route = useRoute()
  const router = useRouter()
  const productId = route.query.productId
  
  // 响应式数据
  const loading = ref(false)
  const dialogVisible = ref(false)
  const previewImageUrl = ref('')
  const majors = ref([])
  const majorsLoading = ref(false)
  const originalImages = ref([])
  
  // 表单数据
  const form = reactive({
    productId: null,
    category: [],
    productName: '',
    price: '',
    introduction: '',
    images: [],
    grade: '',
    major: ''
  })
  
  // 静态数据
  const grades = ['大一', '大二', '大三', '大四', '研一', '研二', '研三']
  const categories = [
    '乐器','数码','艺术品','美妆','书籍',
    '服饰','家居','运动户外','文具','玩具','二手教材'
  ]
  
  // 计算属性
  const showEducationFields = computed(() => 
    form.category.includes('二手教材')
  )
  
  // 验证规则（与发布页面保持一致）
  const rules = reactive({
    category: [{ 
      required: true, 
      message: '请至少选择一个商品类别', 
      trigger: 'change',
      type: 'array',
      validator: (rule, value, callback) => {
        value.length === 0 ? callback(new Error('至少选择一个分类')) : callback()
      }
    }],
    productName: [
      { required: true, message: '请输入商品名称', trigger: 'blur' },
      { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
    ],
    price: [
      { required: true, message: '请输入商品价格', trigger: 'blur' },
      { pattern: /^\d+(\.\d{0,2})?$/, message: '请输入有效的价格格式', trigger: 'blur' }
    ],
    introduction: [
      { required: true, message: '请输入商品描述', trigger: 'blur' },
      { min: 10, message: '至少输入10个字符描述', trigger: 'blur' }
    ],
    images: [{ 
      required: true, 
      validator: (rule, value, callback) => {
        value.length === 0 ? callback(new Error('请至少上传一张图片')) : callback()
      },
      trigger: 'change'
    }]
  })
  
  // 生命周期钩子
  onMounted(async () => {
    await loadMajors()
    await fetchProductDetails()
  })
  
  // 获取商品详情
  const fetchProductDetails = async () => {
    try {
      const { data } = await axios.get('http://localhost:8092/product/getDetailBySingleId', {
        params: { productId: productId }
      })
  
      if (data.code === 200 && data.data.length > 0) {
        const product = data.data[0]
        form.productId = product.productId
        form.category = product.category.split(',')
        form.productName = product.productName
        form.price = product.price
        form.introduction = product.introduction
        form.grade = product.grade || ''
        form.major = product.major || ''
  
        // 处理图片数据
        originalImages.value = product.images.split(',')
        form.images = originalImages.value.map(url => ({
          name: url.split('/').pop(),
          url: `http://localhost:8092${url}`,
          status: 'success'
        }))
      }
    } catch (error) {
      ElMessage.error('获取商品详情失败')
    }
  }
  
  // 图片处理方法
  const handlePictureCardPreview = (file) => {
    previewImageUrl.value = file.url
    dialogVisible.value = true
  }
  
  const handleRemove = (file) => {
    const index = form.images.findIndex(f => f.uid === file.uid)
    form.images.splice(index, 1)
  }
  
  const handleExceed = () => ElMessage.warning('最多只能上传5张图片')
  
  const handleImageChange = (file) => {
    if (!file.raw.type.startsWith('image/')) {
      ElMessage.error('只能上传图片文件')
      return false
    }
    if (file.raw.size > 10 * 1024 * 1024) {
      ElMessage.error('单张图片大小不能超过10MB')
      return false
    }
    return true
  }
  
  // 提交处理
  const handleSubmit = async () => {
    try {
      loading.value = true
      
      const formData = new FormData()
      formData.append('productId', form.productId)
      formData.append('categories', form.category.join(','))
      formData.append('productName', form.productName)
      formData.append('price', form.price)
      formData.append('introduction', form.introduction)
      formData.append('grade', form.grade)
      formData.append('major', form.major)
  
      // 处理新旧图片
      const newImages = form.images
        .filter(file => file.raw)
        .map(file => file.raw)
      
      newImages.forEach(file => formData.append('images', file))
  
      const token = localStorage.getItem('token')
      const { data } = await axios.post('http://localhost:8092/product/update', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${token}`
        }
      })
  
      if (data.code === 200) {
        ElMessage.success('商品修改成功')
        router.push(`/detail?productId=${productId}`)
      }
    } catch (error) {
      ElMessage.error(`修改失败: ${error.response?.data?.message || error.message}`)
    } finally {
      loading.value = false
    }
  }
  
  // 其他方法（与发布页面保持一致）
  const validatePrice = (value) => {
    if (!/^\d*\.?\d{0,2}$/.test(value)) {
      form.price = value.slice(0, -1)
    }
  }
  
  const loadMajors = async () => {
    try {
      majorsLoading.value = true
      const { data } = await axios.get('http://localhost:8092/major/list')
      majors.value = data.map(m => ({ value: m.majorName }))
    } catch (error) {
      ElMessage.error('专业列表加载失败')
    } finally {
      majorsLoading.value = false
    }
  }
  
  const querySearch = (queryString, cb) => {
    const results = queryString
      ? majors.value.filter(m => m.value.includes(queryString))
      : majors.value
    cb(results)
  }
  
  const handleCancel = () => {
    router.go(-1)
  }
  </script>
  
  <style scoped>
  /* 容器样式 */
  .edit-container {
    padding: 40px 20px;
    background: #f5f7fa;
    min-height: calc(100vh - 80px);
    box-sizing: border-box;
  }
  
  /* 主卡片样式 */
  .edit-card {
    max-width: 800px;
    margin: 0 auto;
    border-radius: 12px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
  }
  
  /* 标题样式 */
  .title {
    text-align: center;
    color: #2c3e50;
    margin: 0 0 30px;
    padding: 20px 0;
    font-size: 28px;
    font-weight: 600;
    letter-spacing: 1.5px;
    position: relative;
    background: linear-gradient(to right, #409eff, #67c23a);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
  
  .title::after {
    content: '';
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 3px;
    background: linear-gradient(to right, #409eff, #67c23a);
    border-radius: 2px;
  }
  
  /* 表单容器 */
  .el-form {
    padding: 20px 30px;
  }
  
  /* 分类选择器 */
  .category-select {
    width: 100%;
    margin-bottom: 15px;
  }
  
  .category-select :deep(.el-select__tags) {
    margin-left: -5px;
  }
  
  .category-select :deep(.el-tag) {
    margin: 4px;
    background-color: #ecf5ff;
    border-color: #d9ecff;
    color: #409eff;
    transition: all 0.2s;
  }
  
  .category-select :deep(.el-tag:hover) {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  }
  
  /* 输入框通用样式 */
  .custom-input :deep(.el-input__wrapper),
  .price-input :deep(.el-input__wrapper) {
    padding: 0 15px;
    background: rgba(245, 247, 250, 0.8);
    border-radius: 8px;
    box-shadow: 0 0 0 1px #e4e7ed inset;
    transition: all 0.3s;
  }
  
  .custom-input :deep(.el-input__wrapper:hover),
  .price-input :deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff inset;
  }
  
  .custom-input :deep(.el-input__wrapper.is-focus),
  .price-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px #409eff inset !important;
  }
  
  /* 价格输入特殊样式 */
  .price-input {
    position: relative;
  }
  
  .price-input :deep(.el-input__prefix) {
    display: flex;
    align-items: center;
    padding-right: 10px;
  }
  
  /* 专业选择器 */
  .major-select :deep(.el-input) {
    position: relative;
  }
  
  .major-select :deep(.el-icon) {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    color: #909399;
  }
  
  .major-select :deep(.el-input__inner) {
    padding-left: 35px !important;
  }
  
  /* 文本域样式 */
  .description-input :deep(.el-textarea__inner) {
    background-color: rgba(245, 247, 250, 0.8);
    border-radius: 8px;
    padding: 12px;
    line-height: 1.6;
    box-shadow: 0 0 0 1px #e4e7ed inset;
    transition: all 0.3s;
  }
  
  .description-input :deep(.el-textarea__inner:hover) {
    box-shadow: 0 0 0 1px #409eff inset;
  }
  
  .description-input :deep(.el-textarea__inner:focus) {
    box-shadow: 0 0 0 2px #409eff inset !important;
  }
  
  /* 图片上传组件 */
  .image-uploader {
    width: 100%;
    margin-top: 10px;
  }
  
  .image-uploader :deep(.el-upload) {
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    transition: all 0.3s;
    width: 120px;
    height: 120px;
    background: rgba(255, 255, 255, 0.9);
  }
  
  .image-uploader :deep(.el-upload:hover) {
    border-color: #409eff;
    background: rgba(64, 158, 255, 0.05);
    transform: translateY(-2px);
  }
  
  .uploaded-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
    transition: transform 0.3s;
  }
  
  .uploaded-image:hover {
    transform: scale(1.03);
  }
  
  .image-actions {
    position: absolute;
    right: 8px;
    bottom: 8px;
    display: flex;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.2s;
  }
  
  :deep(.el-upload-list__item:hover) .image-actions {
    opacity: 1;
  }
  
  .image-actions .el-icon {
    background: rgba(0, 0, 0, 0.5);
    padding: 5px;
    border-radius: 4px;
    color: white;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .image-actions .el-icon:hover {
    background: rgba(0, 0, 0, 0.7);
    transform: scale(1.1);
  }
  
  /* 操作按钮区域 */
  .action-buttons {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    position: relative;
  }
  
  .action-buttons::before {
    content: '';
    position: absolute;
    top: -20px;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(to right, transparent 10%, #e4e7ed 50%, transparent 90%);
  }
  
  .cancel-btn {
    width: 120px;
    padding: 12px;
    border: 1px solid #dcdfe6;
    color: #606266;
    transition: all 0.3s;
  }
  
  .cancel-btn:hover {
    border-color: #409eff;
    color: #409eff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  }
  
  .submit-btn {
    width: 120px;
    padding: 12px;
    background: linear-gradient(135deg, #409eff, #66b1ff);
    border: none;
    letter-spacing: 1px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  
  .submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
  
  .submit-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  }
  
  /* 图片预览对话框 */
  .preview-image {
    width: 100%;
    height: 60vh;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .edit-container {
      padding: 20px 10px;
    }
  
    .edit-card {
      margin: 0 10px;
      border-radius: 8px;
    }
  
    .el-form {
      padding: 15px;
    }
  
    .title {
      font-size: 24px;
      margin-bottom: 25px;
    }
  
    .image-uploader :deep(.el-upload) {
      width: 100px;
      height: 100px;
    }
  
    .action-buttons {
      flex-direction: column;
      gap: 12px;
    }
  
    .cancel-btn,
    .submit-btn {
      width: 100%;
      margin: 0;
    }
  }
  
  @media (max-width: 480px) {
    .title {
      font-size: 22px;
    }
  
    .el-form-item__label {
      font-size: 14px;
    }
  
    .category-select :deep(.el-tag) {
      margin: 2px;
      font-size: 12px;
    }
  }
  
  /* 加载动画 */
  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
  
  .submit-btn :deep(.el-icon) {
    animation: spin 1s linear infinite;
    margin-right: 8px;
  }
  
  /* 表单错误提示增强 */
  :deep(.el-form-item__error) {
    padding: 6px 10px;
    background: #fef0f0;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(255, 73, 73, 0.1);
    color: #f56c6c;
    margin-top: 4px;
    position: relative;
  }
  
  :deep(.el-form-item__error::before) {
    content: "⚠️ ";
    margin-right: 4px;
  }
  
  /* 过渡效果 */
  .el-form-item {
    transition: all 0.3s;
  }
  
  .el-upload-list__item {
    transition: all 0.3s;
  }
  
  /* 专业选择器加载状态 */
  .major-select :deep(.el-icon-loading) {
    animation: spin 1s infinite linear;
    margin-right: 5px;
  }
  
  /* 禁用状态优化 */
  .submit-btn.is-disabled {
    opacity: 0.7;
    transform: none !important;
    box-shadow: none !important;
    background: linear-gradient(135deg, #a0cfff, #b3d8ff);
  }
  </style>